﻿using MongoDAO;
using MongoDAO.Exceptions;
using MongoDAO.Repository;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using NUnit.Framework;

namespace MongoDAOTest
{
    [TestFixture]
    public class ExceptionTests : TestBase
    {
        private IRepository<Foo> _repository;

        [SetUp]
        public override void SetUp()
        {
            _repository = new Repository<Foo>(database);
            _repository.RemoveAll();
            _repository.EnsureIndex(IndexKeys<Foo>.Ascending(x => x.Name),
                                    IndexOptions.SetUnique(true));
        }

        public override void TearDown()
        {
            
        }


        [Test]
        [ExpectedException(typeof(DuplicatedKeyException))]
        public void Throw_Exception_Test()
        {
            _repository.Insert(new Foo() { Name = "Test" });
            _repository.Insert(new Foo() { Name = "Test" });
        }

        [Test]
        public void Get_Key_Exception_Test()
        {
            try
            {
                _repository.Insert(new Foo() { Name = "Test" });
                _repository.Insert(new Foo() { Name = "Test" });
            }
            catch (DuplicatedKeyException ex)
            {
                Assert.AreEqual(ex.Key, "Name");
            }
        }

        [Test]
        public void Two_Keys_Exception_Test()
        {
            _repository.EnsureIndex(IndexKeys<Foo>.Ascending(x => x.Bar), IndexOptions.SetUnique(true));
            try
            {
                _repository.Insert(new Foo() { Name = "1", Bar = "Test" });
                _repository.Insert(new Foo() { Name = "2", Bar = "Test" });
            }
            catch (DuplicatedKeyException ex)
            {
                Assert.AreEqual(ex.Key, "Bar");
            }
        }

        public class Foo : TDocument
        {
            public string Name { get; set; }
            public string Bar { get; set; }
            public override object Id { get; set; }
        }
    }

   
}
